package top.limitblog.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import top.limitblog.dao.UserDao;
import top.limitblog.pojo.UsersEntity;

import java.util.List;

/**
 * Created by liuyu on 15/10/2016.
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    public UsersEntity load(String id) {
        return (UsersEntity) this.getCurrentSession().load(UsersEntity.class, id);
    }

    public String save(UsersEntity obj) {
        return (String) this.getCurrentSession().save(obj);
    }

    public void delete(String id) {
        UsersEntity u = this.load(id);
        this.getCurrentSession().delete(u);
    }

    public void saveOrUpdate(UsersEntity obj) {
        this.getCurrentSession().saveOrUpdate(obj);
    }

    public UsersEntity get(String id) {
        return (UsersEntity) this.getCurrentSession().get(UsersEntity.class, id);
    }

    public List<UsersEntity> findAll() {
        List<UsersEntity> users = this.getCurrentSession().createQuery("from UsersEntity").setCacheable(true).list();
        return users;
    }

    public List<UsersEntity> find(String hql, Object[] param) {
        Query query = this.getCurrentSession().createQuery(hql);
        if (null != param && 0 < param.length) {
            for (int i = 0; i < param.length; i++) {
                query.setParameter(i, param[i]);
            }
        }
        return query.list();
    }

    public UsersEntity get(String hql, Object[] param) {
        List<UsersEntity> l = this.find(hql, param);
        if (null != l && 0 < l.size()) {
            return l.get(0);
        } else {
            return null;
        }
    }

    public void flush() {
        this.getCurrentSession().flush();
    }
}
